<script setup lang="ts">
import { useVModel } from '@vueuse/core';
import DeptSelect from '@/components/DeptSelect/index.vue';
import { DeptVO } from '@/api/system/dept/types';

const props = defineProps<{
  modelValue?: any[];
  disabled?: boolean;
}>();
const emit = defineEmits(['update:modelValue', 'update:handlerUserName']);
const data = useVModel(props, 'modelValue', emit);
const deptSelectRef = ref<InstanceType<typeof DeptSelect>>();

const form = reactive({
  coordinators: data.value || []
});

const open = () => {
  deptSelectRef.value.open();
};

const callBack = (dept?: DeptVO[]) => {
  if (!dept || dept.length === 0) {
    return;
  }
  const newCoordinators = dept.map((item) => ({
    handlerUserId: item.deptId,
    handlerUserName: item.deptName,
    completeDay: '',
    orderNo: ''
  }));
  if (data.value && data.value.length > 0) {
    data.value = data.value.concat(
      newCoordinators.filter((newItem) => !data.value.some((existing) => existing.handlerUserId === newItem.handlerUserId))
    );
  } else {
    data.value = newCoordinators;
  }
  form.coordinators = data.value;
};

const handleRemoveCoordinator = (index: number) => {
  data.value.splice(index, 1);
  form.coordinators = data.value;
};

const handleClose = (i: number) => {
  if (props.disabled === false) {
    data.value.splice(i, 1);
    form.coordinators = data.value;
  }
};
</script>

<template>
  <div class="coordinator-container">
    <el-form ref="coordinatorFormRef" :model="form" label-width="80px">
      <el-form-item v-for="(item, i) in data" :key="item.handlerUserId" prop="`coordinators.${i}`">
        <el-row>
          <el-col :span="4">
            <el-input v-model="item.handlerUserName" :disabled="props.disabled" placeholder="请输入协调部门名称" />
          </el-col>
          <el-col :span="8">
            <el-input v-model="item.completeDay" :disabled="props.disabled" placeholder="请输入完成天数" />
          </el-col>
          <el-col :span="8">
            <el-input v-model="item.orderNo" :disabled="props.disabled" placeholder="请输入顺序" />
          </el-col>
          <el-col :span="2">
            <el-button type="danger" size="small" :disabled="props.disabled" @click="handleRemoveCoordinator(i)"> 删除 </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-button plain :disabled="props.disabled" class="add-coordinator-button" @click="open"> +</el-button>
    <dept-select ref="deptSelectRef" :multiple="true" @confirm-call-back="callBack"></dept-select>
  </div>
</template>

<style scoped lang="scss">
.coordinator-container {
  display: flex;
  flex-direction: column;
}

.add-coordinator-button {
  align-self: flex-end;
  margin-top: 10px;
}
</style>
